package top.oneit.jdownload.data.dao;

import cn.hutool.core.collection.CollectionUtil;
import org.hibernate.Session;
import top.oneit.jdownload.constants.JConstants;
import top.oneit.jdownload.data.entity.DownloadSaveStatus;
import top.oneit.jdownload.data.entity.DownloadingTablePo;

import java.util.List;

/**
 * @author lingkang
 * Created by 2021/12/8
 */
public class DownloadSaveStatusDao extends BaseDao {

    public static List<DownloadSaveStatus> getByDownloadingTablePo(DownloadingTablePo po) {
        Session session = getSession();
        session.beginTransaction();
        List<DownloadSaveStatus> list = session.createQuery("from DownloadSaveStatus where downloadingTablePo=:po")
                .setParameter("po", po)
                .list();
        session.getTransaction().commit();
        return list;
    }

    public static void deleteByDownloadingTablePo(DownloadingTablePo po){
        Session session = getSession();
        session.beginTransaction();
        session.createQuery("delete from DownloadSaveStatus where downloadingTablePo=:po")
                .setParameter("po", po).executeUpdate();
        session.getTransaction().commit();
    }

    public static int getDownloadCompleteNumber(DownloadingTablePo downloadingTablePo){
        Session session = getSession();
        session.beginTransaction();
        List<Long> list = session.createQuery("select count(*) from DownloadSaveStatus where downloadingTablePo=:po and status=:status")
                .setParameter("po", downloadingTablePo)
                .setParameter("status", JConstants.FILE_STATUS_FINISH)
                .list();
        session.getTransaction().commit();
        if (CollectionUtil.isEmpty(list)){
            return 0;
        }
        return Integer.valueOf(list.get(0).intValue());
    }

    public static Long getCount(DownloadingTablePo downloadingTablePo){
        Session session = getSession();
        session.beginTransaction();
        List<Long> list = session.createQuery("select count(*) from DownloadSaveStatus where downloadingTablePo=:po")
                .setParameter("po", downloadingTablePo)
                .list();
        session.getTransaction().commit();
        return list.get(0);
    }
}
